﻿using System;
using System.Web;

namespace WebStickyNotes.Helpers
{
    public static class SecurityHelper
    {
        public static void SetSignIn(int currentUserId, int currentUserRole)
        {
            var token = Guid.NewGuid().ToString();
            var session = HttpContext.Current.Session;

            session["WebStickyNotes"] = token;
            session["Current"] = currentUserId;
            session["Role"] = currentUserRole;

            // TODO: store the token against the user in the db for comparion purposes
            session[session.SessionID] = token;
        }

        public static bool IsSignedIn()
        {
            var isSignedIn = false;
            var session = HttpContext.Current.Session;

            if (session["WebStickyNotes"] != null && session["Current"] != null)
            {
                if (session["WebStickyNotes"] == session[session.SessionID])
                {
                    isSignedIn = true;
                }
            }

            return isSignedIn;
        }

        public static int GetSignedInUserId()
        {
            var currentUser = 0;
            var session = HttpContext.Current.Session;

            if (session["WebStickyNotes"] != null && session["Current"] != null)
            {
                if (session["WebStickyNotes"] == session[session.SessionID])
                {
                    currentUser = (int) session["Current"];
                }
            }

            return currentUser;   
        }

        public static int GetSignedInUserRole()
        {
            var currentRole = 0;
            var session = HttpContext.Current.Session;

            if (session["WebStickyNotes"] != null && session["Role"] != null)
            {
                if (session["WebStickyNotes"] == session[session.SessionID])
                {
                    currentRole = (int)session["Role"];
                }
            }

            return currentRole;
        }

        public static void SignOut()
        {
            var session = HttpContext.Current.Session;

            if (session["WebStickyNotes"] != null && session["Current"] != null)
            {
                session.Remove(session.SessionID);

                session.Remove("WebStickyNotes");
                session.Remove("Current");
                session.Remove("Role");
            }
        }
    }
}